package utils;

import cn.hutool.core.convert.Convert;
import enums.DatabaseTypeEnum;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: syh
 * @Date: 2023/12/18/12:06
 */
public class DBUtil {
    public static Connection getConnection(String databaseType) {
        databaseType = databaseType.toLowerCase();
        Connection conn = null;
        try {
            DatabaseTypeEnum databaseTypeEnum = DatabaseTypeEnum.getDatabaseTypeEnum(databaseType);
            Class.forName(databaseTypeEnum.getDriverName());

            Map<String,Object> configMap = YmlUtil.getYmlMap();
            String url = Convert.toStr(configMap.get(databaseType + "-url"));
            String username = Convert.toStr(configMap.get(databaseType + "-userName"));
            String password = Convert.toStr(configMap.get(databaseType + "-password"));
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * ResultSetתMap
     * @param rs
     * @param metaData
     * @return
     * @throws SQLException
     */
    public static Map<String,String> getFieldMap(ResultSet rs, ResultSetMetaData metaData) throws SQLException {
        Map<String,String> map = new HashMap<>();
        int columnCount = metaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnName(i);
            map.put(columnName.toUpperCase(),rs.getString(columnName));
        }

        return map;
    }

    /**
     * 获取数据列表
     * @param rs
     * @param cellIndex
     * @return
     * @throws SQLException
     */
    public static List<List<String>> getList(ResultSet rs,int cellIndex) throws SQLException {
        List<List<String>> dataList = new ArrayList<>();
        while (rs.next()){
            List<String> ele = new ArrayList<>();
            for (int i = 1; i <= cellIndex; i++) {
                ele.add(Convert.toStr(rs.getObject(i),""));
            }
            dataList.add(ele);
        }

        return dataList;
    }
}
